import React from 'react'
import { View, Text, Image } from '@tarojs/components'
import Taro from '@tarojs/taro'
import useNavBarInfo from '../../hook/useNavBarInfo'
import './index.scss'

interface PageWrapperProps {
  title?: string
  showBack?: boolean
  backIcon?: string
  backgroundColor?: string
  color?: string
  onBack?: () => void
  children: React.ReactNode
}

const PageWrapper: React.FC<PageWrapperProps> = ({
                                                   title = '',
                                                   showBack = true,
                                                   backIcon,
                                                   backgroundColor = '#ffffff',
                                                   color = '#000000',
                                                   onBack,
                                                   children
                                                 }) => {
  const {
    statusBarHeightRpx,
    navBarHeightRpx,
    totalHeightRpx
  } = useNavBarInfo()

  const handleBack = () => {
    const pages = Taro.getCurrentPages()
    if (onBack) {
      onBack()
    } else if (pages.length > 1) {
      Taro.navigateBack()
    } else {
      Taro.reLaunch({ url: '/pages/index/index' })
    }
  }

  return (
    <View className="page-wrapper">
      <View
        className="custom-nav-wrapper"
        style={{
          height: `${totalHeightRpx}rpx`,
          backgroundColor,
          color
        }}
      >
        <View
          className="custom-nav"
          style={{
            paddingTop: `${statusBarHeightRpx}rpx`,
            height: `${navBarHeightRpx}rpx`
          }}
        >
          {showBack && (
            <View className="nav-back" onClick={handleBack}>
              <Image
                src={backIcon || require('@/assets/back.png')}
                className="back-icon"
              />
            </View>
          )}
          <View className="nav-title">
            <Text>{title}</Text>
          </View>
          <View className="nav-placeholder" />
        </View>
      </View>

      <View className="page-content" style={{ paddingTop: `${totalHeightRpx}rpx` }}>
        {children}
      </View>
    </View>
  )
}

export default PageWrapper
